﻿using System;
using System.Collections.Generic;

namespace LabyCLI
{
    public class Parser
    {
        private string cmd;
        private List<string> args = new List<string>();

        //Parsing
        private string argBuffer = string.Empty;
        private bool isBetweenQuotes = false;
        private int index = 0;

        public List<string> getArgs()
        {
            return args;
        }

        public string getCmd()
        {
            return cmd;
        }

        public void Parse(string input)
        {
            //Resetting buffer
            reset();
            foreach (char Char in input)
            {
                if (Char.ToString() != " ")
                {
                    addToArgBuffer(Char);
                }
                else
                {
                    if (isBetweenQuotes)
                    {
                        addToArgBuffer(Char);
                    }
                    else
                    {
                        clearArgBuffer();
                    }
                }
            }
                    
            if (argBuffer != string.Empty)
            {
                clearArgBuffer();
            }

            //Extracting the command from the args list, before we remove it..
            cmd = args[0];
            args.RemoveAt(0);
        }

        private void addToArgBuffer(char Char)
        {
            if (Char.ToString() == "\"")
            {
                isBetweenQuotes = !isBetweenQuotes;
            }
            else
            {
                argBuffer += Char.ToString();
            }
        }

        private void reset(){
            cmd = string.Empty;
            args = new List<string>();
            index = 0;
        }

        private void clearArgBuffer()
        {
            //Shifting to the next arg
            args.Insert(index, argBuffer);
            argBuffer = string.Empty;
            index++;
        }
    }
}
